package com.zs.toolbox.web2j.system.core.config.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.zs.toolbox.web2j.db.config.WtDynamicDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author shuai.zhang  on 2018/10/11
 * @description
 */
@Configuration
@MapperScan({"com.zs.toolbox.web2j.system.core.mapper.user", "com.zs.toolbox.web2j.system.core.mapper.other"})
public class ZtSystemDbConfigration {

    @ConfigurationProperties(prefix = "user-datasource")
    @Bean(name = "user-datasource")
    public DruidDataSource userMasterDataSource() throws SQLException {
        return new DruidDataSource();
    }

    @ConfigurationProperties(prefix = "user-datasource-slaver")
    @Bean(name = "user-datasource-slaver")
    public DruidDataSource userSlaverDataSource() throws SQLException {
        return new DruidDataSource();
    }

//    @ConfigurationProperties(prefix = "common-datasource")
//    @Bean(name = "common-datasource")
//    public DruidDataSource commonMasterDataSource() throws SQLException {
//        return new DruidDataSource();
//    }
//
//    @ConfigurationProperties(prefix = "common-datasource-slaver")
//    @Bean(name = "common-datasource-slaver")
//    public DruidDataSource commonSlaverDataSource() throws SQLException {
//        return new DruidDataSource();
//    }

    @Bean(name = "datasource")
    @Primary
    public WtDynamicDataSource dynamicDataSource(
//            @Qualifier("common-datasource-slaver") DataSource commonDatasourceSlaver,
//            @Qualifier("common-datasource") DataSource commonDatasourceMaster,
            @Qualifier("user-datasource-slaver") DataSource userDatasourceSlaver,
            @Qualifier("user-datasource") DataSource userDatasourceMaster
    ) {

        WtDynamicDataSource bean = new WtDynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
//        targetDataSources.put(DBTypeEnum.DB_COMMON_DATASOURCE,commonDatasourceMaster);
//        targetDataSources.put(DBTypeEnum.DB_COMMON_DATASOURCE_SLAVER,commonDatasourceSlaver);
        targetDataSources.put(DBTypeEnum.DB_USER_DATASOURCE,userDatasourceMaster);
        targetDataSources.put(DBTypeEnum.DB_USER_DATASOURCE_SLAVER,userDatasourceSlaver);
        bean.setTargetDataSources(targetDataSources);
        bean.setDefaultTargetDataSource(userDatasourceMaster);

        return bean;
    }

}
